package com.zkingsoft.command.impl;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zkingsoft.command.AbstractCommand;

public class UploadFileCommandImpl extends AbstractCommand {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
		String realPath = request.getServletContext().getRealPath("/WEB-INF/fileupload/");
		System.out.println("realPath == " + realPath);
		List<FileItem> fileList = fileUpload.parseRequest(request);
		if(fileList != null) {
			for(int i = 0; i < fileList.size(); i++) {
				FileItem item = fileList.get(i);
				
				if(item.isFormField()) {
					//普通表单参数
					System.out.println("fileName == " + item.getFieldName());//请求参数名
					System.out.println("value == " + item.getString());//请求参数值
				} else {
					//上传的文件
					String fileName = item.getName();
					//生成新的文件名: 当前系统时间.后缀名
					realPath = realPath+"/"+ fileName;
					OutputStream output = null;
					InputStream input = item.getInputStream();
					try {
						output = new BufferedOutputStream(
										new FileOutputStream(realPath));
						byte[] tmp = new byte[1024];
						int len = 0;
						while((len = input.read(tmp)) != -1) {
							output.write(tmp, 0, len);
						}
					} catch(IOException ex) {
						ex.printStackTrace();
					} finally {
						if(input != null) {
							input.close();
						}
						if(output != null) {
							output.close();
						}
					}
				}
			}
		}
		
		
	}

}
